from wxpy import *
import requests
import json


def robot(param, province, city):
    data = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": param
            },
            "inputImage": {
                "url": param
            },
            "selfInfo": {
                "location": {
                    "city": city or '上海',
                    "province": province or '上海',
                    # "street": "虹漕路"
                }
            }
        },
        "userInfo": {
            "apiKey": "cd328433aa3b9646743e2abc3d1a2286",
            "userId": "6072C7CAF1FE468A8B36FE4DD0F03E92"
        }
    }
    info = json.dumps(data)
    res = requests.post('http://openapi.tuling123.com/openapi/api/v2', data=info)
    res = json.loads(res.content.decode())
    str = ''
    results = res['results']
    results.reverse()
    for item in results:
        if item['resultType'] == 'text':
            str += item['values']['text'] + '\n'
        else:
            str += '你要找的都在这：<br>' + item['values']['url']
    return str


bot = Bot(cache_path=True)
my_friends = bot.friends(update=True)


@bot.register(my_friends)
def my_friednd_message(msg):
    print('[接收]' + str(msg))
    try:
        sender = bot.user_details(msg.sender)
        if msg.type == 'Text':  # 除文字外其他消息回复内容
            ret = robot(msg.text, sender.province, sender.city)
        else:
            ret = '可以发文字吗？(#^.^#)[拜托]'
        print('[发送]' + ret)
    except Exception as e:
        print(e)
    return ret


# 进入交互式的 Python 命令行界面，并堵塞当前线程
embed()
